<?php

namespace App\Model;

use App\Exceptions\BizException;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Auth;

class Users extends User
{
    public $table = 'users';

    protected $fillable = [
        'username', 'email', 'password', 'nickname',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function login($username, $password)
    {
        $user = self::where('username', $username)->first();
        if (empty($user)) {
            $url = env('YFK_URL') . '/tp/admin.php?m=Api&a=userLogin';
            $apiResJson = Common::postCurl($url, [
                'username' => $username,
                'password' => $password,
            ]);
            $apiRes = json_decode($apiResJson, true);

            if ($apiRes['status'] === 1) {
                self::create(['username' => $username, 'password' => bcrypt($password)]);
                Auth::attempt(['username' => $username, 'password' => $password]);
            } else {
                throw new BizException('用户名或密码错误');
            }
        } else {
            $res = Auth::attempt(['username' => $username, 'password' => $password]);
            if (empty($res)) {
                throw new BizException('密码错误');
            }
        }
    }

    public static function register($username, $password)
    {
        self::create(['username' => $username, 'password' => bcrypt($password)]);

        $url = env('YFK_URL') . '/tp/admin.php?m=Api&a=userRegister';
        Common::postCurl($url, [
            'username' => $username,
            'password' => $password,
        ]);
    }

    public static function checkMobileExist($mobile)
    {
        $user = self::where('username', $mobile)->first();
        if ($user)
            return true;

        $url = env('YFK_URL') . '/tp/admin.php?m=Api&a=checkMobileExist';
        $apiResJson = Common::postCurl($url, [
            'mobile' => $mobile,
        ]);
        $apiRes = json_decode($apiResJson, true);

        if ($apiRes['status'] == 1) {
            return true;
        } else {
            return false;
        }
    }
}
